class Solution
{
public:
    int myAtoi(string s)
    {
        int n = s.size();
        int result = 0;
        bool postive = true;
        int i = 0;

        // skip space
        while (i < n && s[i] == ' ')
        {
            ++i;
        }

        // check sign
        if (i == n)
        {
            return 0;
        }
        if (s[i] == '-')
        {
            postive = false;
            ++i;
        }
        else if (s[i] == '+')
        {
            ++i;
        }

        // read nums
        int limit = INT_MAX / 10; // 214748364
        while (i < n)
        {
            char c = s[i];
            if (s[i] < '0' || s[i] > '9')
            {
                break;
            }
            int num = static_cast<int>(c - '0');
            if (result > limit)
            {
                if (postive)
                {
                    return INT_MAX;
                }
                else
                {
                    return INT_MIN;
                }
            }
            else if (result == limit)
            {
                if (postive && num >= 7)
                {
                    return INT_MAX;
                }
                else if (!postive && num >= 8)
                {
                    return INT_MIN;
                }
            }
            result *= 10;
            result += num;
            ++i;
        }

        // sign
        if (!postive)
        {
            result = -result;
        }
        return result;
    }
};